package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.db.DictionaryHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.chatting.InviteAttentionActivity;
import com.yksj.healthtalk.ui.doctor.DoctorSearchResultActivity;
import com.yksj.healthtalk.ui.friend.FriendCharacterTagFragment.onBackListener;
import com.yksj.healthtalk.ui.views.RangeSeekBar;
import com.yksj.healthtalk.ui.views.RangeSeekBar.OnRangeSeekBarChangeListener;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.WheelUtils;

/**
 * @ClassName: FriendSearchAboutFriendActivity
 * @Description: 按条件搜索
 * @author wangtao wt0710910108@163.com
 * @date 2013-1-19 上午10:18:28
 */
public class FriendSearchAboutFriendActivity extends BaseFragmentActivity implements OnClickListener, onBackListener {
	private DictionaryHelper dictionaryHelper;
	private final int WHAT_CITY = 1;
	private View mainView;
	private final int DIALOG_QUERY = 001;
	private PopupWindow pop;
	private View wheelView;
	private String areaCode;// 区域编码
	private Map<String, List<Map<String, String>>> cityMap = new HashMap<String, List<Map<String, String>>>();
	private List<Map<String, String>> proList = new ArrayList<Map<String, String>>();
	private Map<String, List<Map<String, String>>> infolayMap = new HashMap<String, List<Map<String, String>>>();
	private String tagsCode;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WHAT_CITY:
				removeDialog(DIALOG_QUERY);
				break;
			}
		};
	};
	private TextView mSexTextView;
	private TextView mAgeTextView;
	private TextView mAttentionTextView;
	private TextView mLocaleTextView;
	private TextView mCacheTextView;
	private TextView mLablesTextView;// 个性标签
	private CustomerInfoEntity mCustomerInfoEntity;// 用户对象
	private Boolean isFromChat = false;
	private Boolean isFromMyPatient = false;//是否是我的患者中的搜素
	private FriendCharacterTagFragment fragment;
	private FragmentManager f;
	private RangeSeekBar<Integer> seekBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		dictionaryHelper = DictionaryHelper.getInstance(this);
		setContentView(R.layout.friend_search_aboutfriend);

		if (proList == null || proList.size() == 0) {
			showDialog(DIALOG_QUERY);
			queryData();
		}
		initWidget();
		initData();
	}

	private void initData() {
		if (getIntent().hasExtra("type")) {
			isFromChat = true;
			titleTextV.setText("条件邀请");
		}else if(getIntent().hasExtra("search_type") && getIntent().getExtras().getInt("search_type") == 0 ){
			isFromMyPatient = true;
		}
		// 另增加布局文件
		LayoutInflater inflater = LayoutInflater.from(this);
		mainView = inflater.inflate(R.layout.advert_layout, null);
		wheelView = inflater.inflate(R.layout.wheel, null);
		Button wheelCancel = (Button) wheelView.findViewById(R.id.wheel_cancel);
		Button wheelSure = (Button) wheelView.findViewById(R.id.wheel_sure);
		pop = new PopupWindow(wheelView, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);

		// 监听器
		wheelCancel.setOnClickListener(this);
		wheelSure.setOnClickListener(this);

		// 获取对象数值
		mCustomerInfoEntity = getIntent().getParcelableExtra(
				"mCustomerInfoEntity");
		if (mCustomerInfoEntity == null && isFromChat == true) {
			mCustomerInfoEntity = new CustomerInfoEntity();
		}
			// 默认0是找朋友 1 是找医生
			mCustomerInfoEntity.setType(0);
			// 性别
			mSexTextView.setTextColor(getResources().getColorStateList(
					R.color.tag_note));
			if (mCustomerInfoEntity.getSex() != null
					&& !mCustomerInfoEntity.getSex().equals("")) {
				// 性别 0--全部 1--男 2--女
				if (mCustomerInfoEntity.getSex().equalsIgnoreCase("1")) {
					mSexTextView.setText("男");
				} else if (mCustomerInfoEntity.getSex().equalsIgnoreCase("2")) {
					mSexTextView.setText("女");
				} else {
					mSexTextView.setText("全部");
					mSexTextView.setTextColor(getResources().getColorStateList(
							R.color.tab_txt_gray));
				}
			}
			// 年龄
			if (mCustomerInfoEntity.getMaxAge() != 0) {
				mAgeTextView.setText(mCustomerInfoEntity.getMinAge() + "~"
						+ mCustomerInfoEntity.getMaxAge());
				mAgeTextView.setTextColor(getResources().getColorStateList(
						R.color.tag_note));
			}
			seekBar = new RangeSeekBar<Integer>(0, 100, this);
			if (mCustomerInfoEntity.getMaxAge() != 0) {
				seekBar.setSelectedMinValue(mCustomerInfoEntity.getMinAge());
				seekBar.setSelectedMaxValue(mCustomerInfoEntity.getMaxAge());
			}
			 ViewGroup layout = (ViewGroup) findViewById(R.id.layout);
		      layout.addView(seekBar);
			// 地点
			if (mCustomerInfoEntity.getAreaName() != null
					&& !mCustomerInfoEntity.getAreaName().equals("")) {
				mLocaleTextView.setText(mCustomerInfoEntity.getAreaName());
				mLocaleTextView.setTextColor(getResources().getColorStateList(
						R.color.tag_note));
			}
			// 个性标签
			if (mCustomerInfoEntity.getInterestCode() != null
					&& !mCustomerInfoEntity.getInterestCode().equals("")) {
				mLablesTextView.setText(mCustomerInfoEntity.getInterestName());
				mLablesTextView.setTextColor(getResources().getColorStateList(
						R.color.tag_note));
			}
	}

	private void initWidget() {
		initTitle();
		
		setBackBtn("返回",this);
		
		setTitle("按条件搜索");
		
		setRight("确定",this);
		 
		mSexTextView = (TextView) findViewById(R.id.find_sex);
		mAgeTextView = (TextView) findViewById(R.id.find_age);
		mLocaleTextView = (TextView) findViewById(R.id.find_locale);
		mLablesTextView = (TextView) findViewById(R.id.lables_tv);

		mSexTextView.setOnClickListener(this);
		mAgeTextView.setOnClickListener(this);
		mLocaleTextView.setOnClickListener(this);
		mLablesTextView.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
	}

	private void queryData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				dictionaryHelper.setInfolayData(FriendSearchAboutFriendActivity.this, infolayMap);
				if (proList.size() == 0) {
					setCityData();
				}
			}

		}).start();

	}

	/**
	 * 设置滚轮 城市数据
	 */
	private void setCity() {
		mCacheTextView = mLocaleTextView;
		// code = mCityCode;
		WheelUtils.setDoubleWheel(this, proList, cityMap, mainView, pop,
				wheelView);
	}

	/**
	 * 创建窗口
	 */
	public Dialog onCreateDialog(int id) {
		Dialog dia = null;
		switch (id) {
		case DIALOG_QUERY:
			dia = getDialogByConnectProgress(DIALOG_QUERY);
			break;
		default:
			break;
		}
		return dia;
	}

	/**
	 * 连接进度条
	 * 
	 * @return
	 */
	private Dialog getDialogByConnectProgress(int id) {
		ProgressDialog progressDialog = new ProgressDialog(this);
		String message = "正在加载数据.....请稍侯！";
		progressDialog.setMessage(message);
		progressDialog.setCancelable(true);
		return progressDialog;
	}

	private void setCityData() {
		// if(!proList.isEmpty())
		// return;
		cityMap = new HashMap<String, List<Map<String, String>>>();
		proList = DictionaryHelper.getInstance(this).setCityData(this, cityMap);
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("name", getString(R.string.limit_no));
		hashMap.put("code", "0");
		// 每项加个全部
		for (Map<String, String> map : proList) {
			String name = map.get("name");
			cityMap.get(name).add(0, hashMap);
		}
		proList.add(0, hashMap);

		List<Map<String, String>> arr = new ArrayList<Map<String, String>>();
		arr.add(hashMap);
		cityMap.put(getString(R.string.limit_no), arr);
		// isLoad = true;
		handler.sendEmptyMessage(WHAT_CITY);
	}

	@Override
	public void onClick(View v) {
		findViewById(R.id.range_seek_bar).setVisibility(View.GONE);
		switch (v.getId()) {
		case R.id.wheel_cancel:
			if (pop != null) {
				pop.dismiss();
			}
			break;
		case R.id.find_sex:
			setSex();
			break;
		case R.id.find_age:
//			setAge();
//			mCustomerInfoEntity.getMinAge() + "~"
//			+ mCustomerInfoEntity.getMaxAge()
			View seek = findViewById(R.id.range_seek_bar);
			if (seek.getVisibility() == View.GONE) {
				seek.setVisibility(View.VISIBLE);
			}else {
				seek.setVisibility(View.GONE);
			}
	        seekBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
	                @Override
	                public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
	                        mCustomerInfoEntity.setMinAge(minValue);
	                        if (maxValue == 0) {
	                        	 mCustomerInfoEntity.setMaxAge(100);
	                        	  mAgeTextView.setText(minValue+"~"+100);
							}else {
			                       mCustomerInfoEntity.setMaxAge(maxValue);
			                       mAgeTextView.setText(minValue+"~"+maxValue);
							}
	                      
	                }
	        });
			break;
		case R.id.find_att:
			break;
		case R.id.find_locale:
			setCity();
			break;
		case R.id.lables_tv:
			f = getSupportFragmentManager();
			FragmentTransaction transaction = f.beginTransaction();
			fragment = (FriendCharacterTagFragment) FriendCharacterTagFragment
					.getInstance(mLablesTextView.getText().toString().trim());
			transaction.setCustomAnimations(R.anim.slide_in_left,
					R.anim.slide_out_right);
			transaction.addToBackStack(null);
			transaction.replace(android.R.id.content, fragment);
			// transaction.add(fragment, "FriendCharacterTagFragment");
			transaction.commit();
			break;
		case R.id.wheel_sure:
			if (pop != null) {
				pop.dismiss();
			}
			mCacheTextView.setText(WheelUtils.getCurrent());
			mCacheTextView.setTextColor(getResources().getColorStateList(
					R.color.tag_note));
			if (mCacheTextView == mLocaleTextView) {
				areaCode = WheelUtils.getCode();
				if ("".equals(areaCode))
					areaCode = WheelUtils.getFirstCode();
				else
					areaCode = WheelUtils.getCode();
			}
			break;
		// 确定键
		case R.id.title_right2:
			Intent intent;
			beginSearchFriends();
			if (isFromChat) {
				intent = getIntent();
				intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
				intent.putExtra("type", 3);
				intent.setClass(this, InviteAttentionActivity.class);
				startActivity(intent);
			} else if(isFromMyPatient){
				intent = new Intent(this, DoctorSearchResultActivity.class);
				intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
				startActivity(intent);
			}else {
				intent = new Intent(this, FriendSearchMainActivity.class);
				intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
				setResult(0, intent);
				finish();
			}
			break;
		case R.id.title_back:
			setResult(-1);
			finish();
			break;
		}
	}

	/**
	 * 搜索好友
	 */
	private void beginSearchFriends() {
		if (mCustomerInfoEntity == null) {
			mCustomerInfoEntity = new CustomerInfoEntity();
		}
		// 经历和医生默认
		FriendUtil.setCustomerInfoEntityOthersDefault(mCustomerInfoEntity, 1);
		mCustomerInfoEntity.setUsername("");

		// 性别
		String sex = "";
		if ((sex = mSexTextView.getText().toString().trim()).equals("男")) {
			mCustomerInfoEntity.setSex("1");
		} else if (sex.equals("女")) {
			mCustomerInfoEntity.setSex("2");
		} else {
			mCustomerInfoEntity.setSex("");
		}

		// 年龄
		if (!(mAgeTextView.getText().toString().trim().equals("全部")
				|| mAgeTextView.getText().toString().trim().equals("") || mAgeTextView
				.getText().toString().trim().equals("0~100"))) {
			String[] strs = mAgeTextView.getText().toString().trim().split("~");
			if (strs.length == 1) {
				mCustomerInfoEntity.setMinAge(50);
				mCustomerInfoEntity.setMaxAge(100);
			}
			try {
				mCustomerInfoEntity.setMinAge(Integer.valueOf(strs[0]));
				mCustomerInfoEntity
						.setMaxAge(mCustomerInfoEntity.getMinAge() == 50 ? Integer
								.valueOf(strs[1].substring(0, 3)) : Integer
								.valueOf(strs[1].substring(0, 2)));
			} catch (Exception e) {
			}
		} else {
			mCustomerInfoEntity.setMinAge(0);
			mCustomerInfoEntity.setMaxAge(100);
		}

		// 地点
		if (!mLocaleTextView.getText().toString().trim().equals("")
				&& areaCode != null) {
			mCustomerInfoEntity.setAreaCode(Integer.valueOf(areaCode));
			mCustomerInfoEntity.setAreaName(mLocaleTextView.getText()
					.toString());
		} else {
			mCustomerInfoEntity.setAreaCode(0);
			mCustomerInfoEntity.setAreaName(getString(R.string.limit_no));
		}

		// 个性标签
		String title;
		if (!mLablesTextView.getText().toString().trim().equals("全部")) {
			mCustomerInfoEntity.setInterestName(mLablesTextView.getText()
					.toString());
			mCustomerInfoEntity.setInterestCode(tagsCode);
		} else if (mLablesTextView.getText().toString().trim().equals("全部")) {
			mCustomerInfoEntity.setInterestName("全部");
			mCustomerInfoEntity.setInterestCode("");
		}

	}

	/**
	 * 设置滚轮 性别
	 */
	private void setSex() {
		mCacheTextView = mSexTextView;
		String[] ages = { "男", "女", "全部" };
		WheelUtils.setSingleWheel(this, ages, mainView, pop, wheelView, false);
	}

	/**
	 * 设置滚轮 年龄数据
	 */
	private void setAge() {
		mCacheTextView = mAgeTextView;
		final String[] ages = { "全部", "0~17岁", "18~25岁", "26~36岁", "37~50岁",
				"大于50岁" };
		WheelUtils.setSingleWheel(this, ages, mainView, pop, wheelView, false);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(-1);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBack(String str, String code) {
		if (fragment != null && !TextUtils.isEmpty(str)) {
			mLablesTextView.setText(str);
			mLablesTextView.setTextColor(getResources().getColorStateList(
					R.color.tag_note));
			tagsCode = code;
		}
		FragmentTransaction fragmentTransaction = f.beginTransaction();
		fragmentTransaction.setCustomAnimations(R.anim.slide_in_left,
				R.anim.slide_out_right);
		fragmentTransaction.remove(fragment);
		fragmentTransaction.commit();
	}

	@Override
	public void onBackPressed() {
		if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
			onBack(fragment.getTagToStr(), fragment.getTagCodeToStr());
		} else {
			setResult(-1);
			finish();
		}
	}

}
